<?php

declare(strict_types=1);

namespace Frontend\Middleware;

use Frontend\Http\ApiClient;

class Auth
{
    private static ?array $cachedUser = null;

    public static function currentUser(ApiClient $client): ?array
    {
        if (self::$cachedUser !== null) {
            return self::$cachedUser;
        }
        if (empty($_COOKIE['access_token'])) {
            return null;
        }
        $response = $client->get('/auth/me');
        if ($response['status'] === 200 && is_array($response['data'])) {
            self::$cachedUser = $response['data'];
            return self::$cachedUser;
        }
        return null;
    }

    public static function requireLogin(ApiClient $client): array
    {
        $user = self::currentUser($client);
        if (!$user) {
            header('Location: /login?next=' . urlencode($_SERVER['REQUEST_URI']));
            exit;
        }
        return $user;
    }

    public static function requireAdmin(ApiClient $client): array
    {
        $user = self::requireLogin($client);
        if (($user['role'] ?? '') !== 'admin') {
            http_response_code(403);
            require __DIR__ . '/../Views/pages/403.php';
            exit;
        }
        return $user;
    }

    public static function logout(): void
    {
        foreach (['access_token', 'refresh_token'] as $cookie) {
            setcookie($cookie, '', [
                'expires' => time() - 3600,
                'path' => '/',
            ]);
        }
        self::$cachedUser = null;
    }
}

